#! /bin/sh
# 全局初始化部分.
init()
{
	# app name
	if [ -z "$1" ]; then 
	    echo "usage: $0 <appname> [logfile]"
	    exit 1
	fi
	appname=$1	

	shift

	#. perf log name
	perflog=
	[ -n "$1" ] && perflog=$1

	# verify out perf log name
	[ -z "$perflog" ] && perflog=$appname.txt
	echo "stat the process $appname"
}

# 性能数据头
write_head_i()
{
#	echo "-----------------------------" >>$perflog
#	echo "\Process($appname)\ID Process" >> $perflog
#	echo "\Process($appname)\Handle Count" >> $perflog
#	echo "\Process($appname)\Thread count" >> $perflog
#	echo "\Process($appname)\VIRT" >> $perflog
#	echo "\Process($appname)\RES" >> $perflog
#	echo "\Process($appname)\% Processor Time" >> $perflog
	echo "Time	ID Process	Handle Count	Thread count	VIRT(M)	RES(M)	 % Processor Time	free M	cached(M)	io-read	io-write" >> $perflog
}

#根据进程ID获取内存占用(KB)
function GetWMem  #PID
{
    MEMUsage=`ps -o rss -p $pid|grep -v RSS`
    (( MEMUsage /= 1024))   
    echo $MEMUsage  
}

function GetVMem  #PID
{
    MEMUsage=`ps -o vsz -p $pid|grep -v VSZ`
    (( MEMUsage /= 1024))   
    echo $MEMUsage  
}

function GetHandle  #PID
{
    Handle=`ls /proc/$pid/fd -l|grep socket:|wc -l`
    echo $Handle  
}


# 性能数据内容
write_data()
{	
  vmem=`GetVMem $PID`					#获取虚拟内存占用
  wmem=`GetWMem $PID`					#获取物理内存占用
  handle=`GetHandle $PID`
  now=$(date +"%Y/%m/%d %H:%M:%S")
  top_result=$(top -p $pid -n 1 -b | grep $appname)
  thread_cnt=$(awk '{print $20}' /proc/$pid/stat)
  VIRT=$vmem
  RES=$wmem
  Handle=$handle
  proc_time=$(echo "$top_result" | awk '{print $9}')
  free_m=$(free -m | sed -n 3p | awk '{print $4}')
  cached_m=$(free -m | sed -n 2p | awk '{print $7}')
  #io_w_wait=$(iostat -x | sed -n 7p | awk '{print $12}')
  #io_util=$(iostat -x | sed -n 7p | awk '{print $14}')
  out_line=$(printf "%-s	%-d	%-d	%-d	%-s	%-s	%.2f	%d	%d" "$now" $pid "$Handle" $thread_cnt "$VIRT" "$RES" "$proc_time" $free_m $cached_m) 
  echo "$out_line" >> $perflog
  echo $out_line
}

# 依次记录每个进程的信息
record_all_process()
{
	myFile="./perf_stat.txt"
	myNum="0"
	# 定义一个次数数组.
	for i in `seq 100`
	do
		let cnt_$i=0
	done
	
	# 备份基本的性能LOG文件名.
	ORG_PERFLOG=$perflog
	
	while : 
	do
    pids=$(ps -A | grep "\b$appname\b" | awk '{print $1}')
    ix=1
    for p in $pids
		do	
			if [ -f "$myFile" ];then
			myNum="1"
			break
			fi
			cur_cnt=$(eval echo \${cnt_$ix})
			[ $ix -ge 2 ] && perflog=$ORG_PERFLOG#$ix || perflog=$ORG_PERFLOG
			[ $cur_cnt -eq 0 ] && write_head_i
			pid=$p
			write_data			
			let cnt_$ix=`expr $cur_cnt + 1`
			(( ix++ ))
		done
	if [ $myNum == "1" ];then
	break
	fi
    sleep 1
	done

}


# *************************************
# main 运行 nohup sh mem.sh pid(例如：1652) a.txt(结果文件) &
# *************************************
init $@
record_all_process
exit 0
